package com.hexinfo.dmpro.monitor.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hexinfo.dmpro.common.base.BaseService;
import com.hexinfo.dmpro.common.utils.StringUtils;
import com.hexinfo.dmpro.monitor.dao.CmSwitchDao;
import com.hexinfo.dmpro.monitor.model.CmConfigModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
@Service
public class CmSwitchService extends BaseService {

    @Autowired
    private CmSwitchDao cmSwitchDao;

    @Autowired
    private RestTemplate restTemplate;

    final private int SUCESS_CODE = 200;
    final private int EXCEPTION_CODE = 400;

    public static final String SERVICE_HIVE = "hive";
    public static final String SERVICE_IMPALA = "impala";

    /**
     * 获取CM配置信息
     *
     * @return
     */
    public List<Map<String, String>> getCmConfigInfo(String cmFlag, String clusterFlag, String type) {
        List<Map<String, String>> monitorReqList = new ArrayList<>();
        Map<String, String> map = new HashMap();
        map.put("centerId", "1");
        map.put("monitorFlag", "1");//cm查询特定条件
        map.put("cmFlag", cmFlag);
        map.put("clusterFlag", clusterFlag);
        List<CmConfigModel> monitorBaseModels = cmSwitchDao.selectCmServerConfig(map);
        if (monitorBaseModels != null && monitorBaseModels.size() > 0) {
            for (CmConfigModel monitorBaseModel : monitorBaseModels) {
                Map<String, String> configMap = new HashMap<>();
                JSONObject jsonObject = JSONObject.parseObject(monitorBaseModel.getOtherParam());
                configMap.put("url", jsonObject.get("cmApi").toString());
                configMap.put("user", jsonObject.get("user").toString());
                configMap.put("password", jsonObject.get("password").toString());
                configMap.put("cmFlag", monitorBaseModel.getCmFlag());
                configMap.put("cmName", monitorBaseModel.getCmName());
                configMap.put("clusterFlag", monitorBaseModel.getClusterFlag());
                configMap.put("clusterName", monitorBaseModel.getClusterName());
                if("impala".equals(type) || "yarn".equals(type) || "hive".equals(type)) {
                    String serviceName = cmSwitchDao.selectServiceName(monitorBaseModel.getCmFlag(), monitorBaseModel.getClusterFlag(), type);
                    log.info("cmFlag:" + cmFlag);
                    log.info("clusterFlag:" + clusterFlag);
                    log.info("serviceName" + serviceName);
                    if(StringUtils.isNotBlank(serviceName)) {
                        configMap.put("serviceName", serviceName);
                    } else {
                        continue;
                    }
                }
                Object rangerApi = jsonObject.get("rangerApi");
                Object rangerUsername = jsonObject.get("rangerUsername");
                Object rangerPassword = jsonObject.get("rangerPassword");
                if(null != rangerApi) {
                        configMap.put("rangerApi",jsonObject.get("rangerApi").toString());
                } else {
                    configMap.put("rangerApi","");
                }
                if(null != rangerUsername) {
                    configMap.put("rangerUsername",jsonObject.get("rangerUsername").toString());
                } else {
                    configMap.put("rangerUsername","");
                }
                if(null != rangerPassword) {
                    configMap.put("rangerPassword",jsonObject.get("rangerPassword").toString());
                } else {
                    configMap.put("rangerPassword","");
                }
                monitorReqList.add(configMap);
            }
        }
        return monitorReqList;
    }

    /**
     * 发送请求
     *
     * @param url      url
     * @param paramMap 参数
     * @param method   类型
     */
    public Map<String, Object> sendRequest(String url, Map<String, Object> paramMap, HttpMethod method, String user, String password) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        try {
            headers.set("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            log.error("Authorization异常", e);
        }
        HttpEntity<String> formEntity;
        if (paramMap.isEmpty()) {
            formEntity = new HttpEntity<String>(null, headers);
        } else {
            JSONObject jsonObj = new JSONObject(paramMap);
            formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        }
        ResponseEntity<String> responseData = null;
        Map<String, Object> map = new HashMap<>();
        try {
            responseData = restTemplate.exchange(url, method, formEntity, String.class);
            map.put("code", responseData.getStatusCodeValue());
            map.put("body", responseData.getBody());
        } catch (Exception e) {
//            log.error("调用接口获取数据失败:{}" + e);
//            log.error("当前请求url为:{}" + url);
            map.put("code", EXCEPTION_CODE);
            map.put("reason", e);
        }
        return map;
    }


}
